package cn.iocoder.boot.springai001.repository;

import cn.iocoder.boot.springai001.entity.ChatSessionEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 聊天会话数据访问层
 * <p>
 * 提供会话信息的数据库操作
 */
@Repository
public interface ChatSessionRepository extends JpaRepository<ChatSessionEntity, String> {

    /**
     * 查询用户的所有会话（按最后活跃时间倒序）
     */
    List<ChatSessionEntity> findByUserIdAndDeletedFalseOrderByLastActiveAtDesc(String userId);

    /**
     * 查询用户指定类型的会话
     */
    List<ChatSessionEntity> findByUserIdAndSessionTypeAndDeletedFalseOrderByLastActiveAtDesc(
            String userId, String sessionType);

    /**
     * 按名称搜索会话
     */
    @Query("SELECT s FROM ChatSessionEntity s WHERE s.userId = ?1 AND s.deleted = false " +
           "AND s.sessionName LIKE %?2% ORDER BY s.lastActiveAt DESC")
    List<ChatSessionEntity> searchBySessionName(String userId, String keyword);

    /**
     * 查询用户最近活跃的会话
     */
    @Query("SELECT s FROM ChatSessionEntity s WHERE s.userId = ?1 AND s.deleted = false " +
           "ORDER BY s.lastActiveAt DESC")
    List<ChatSessionEntity> findRecentSessions(String userId);

    /**
     * 查询用户置顶的会话
     */
    List<ChatSessionEntity> findByUserIdAndPinnedTrueAndDeletedFalseOrderByLastActiveAtDesc(String userId);

    /**
     * 查询指定时间之后活跃的会话数量
     */
    long countByUserIdAndDeletedFalseAndLastActiveAtAfter(String userId, LocalDateTime threshold);

    /**
     * 根据 conversationId 查询会话
     */
    Optional<ChatSessionEntity> findByConversationIdAndDeletedFalse(String conversationId);

    /**
     * 统计用户的会话数量
     */
    long countByUserIdAndDeletedFalse(String userId);

    /**
     * 按类型统计
     */
    @Query("SELECT s.sessionType, COUNT(s) FROM ChatSessionEntity s " +
           "WHERE s.userId = ?1 AND s.deleted = false GROUP BY s.sessionType")
    List<Object[]> countByUserIdGroupByType(String userId);
}

